package at.jku.ssw.fortress.builder;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;

public class FortressNature implements IProjectNature {
	public static final String NATURE_ID = "at.jku.ssw.fortress.nature";

	private IProject project;

	public void configure() throws CoreException {
		// Add nature-specific information
		// for the project, such as adding a builder
		// to a project's build spec.
		FortressBuilder.appendTo(project);
	}

	public void deconfigure() throws CoreException {
		FortressBuilder.removeFrom(project);
	}

	public IProject getProject() {
		return project;
	}

	public void setProject(IProject project) {
		this.project = project;
	}

	public static void appendTo(IProject project) throws CoreException {
		Assert.isNotNull(project);
		IProjectDescription description = project.getDescription();
		String[] natures = description.getNatureIds();

		for (String nature : natures) {
			if (nature.equals(NATURE_ID)) {
				return;
			}
		}

		// Add nature to project
		String[] newNatures = new String[natures.length + 1];
		System.arraycopy(natures, 0, newNatures, 0, natures.length);
		// Append it at the end.
		newNatures[natures.length] = NATURE_ID;
		description.setNatureIds(newNatures);
		project.setDescription(description, null);
	}

	public static void removeFrom(IProject project) throws CoreException {
		Assert.isNotNull(project);
		IProjectDescription description = project.getDescription();
		String[] natures = description.getNatureIds();

		for (int i = 0; i < natures.length; ++i) {
			if (natures[i].equals(NATURE_ID)) {
				String[] newNatures = new String[natures.length - 1];
				System.arraycopy(natures, 0, newNatures, 0, i);
				System.arraycopy(natures, i + 1, newNatures, i, natures.length
						- i - 1);
				description.setNatureIds(newNatures);
				project.setDescription(description, null);
				return;
			}
		}
	}
}
